package com.block.channel.flow.channel;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.channel.enums.BaiduAccountEnum;
import com.block.channel.flow.IChannelReportService;
import com.block.channel.model.result.ReprotFlowResult;
import com.block.common.bean.CommonParam;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelActionMonitorRecord;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.mapper.ChannelActionMonitorRecordMapper;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * http://ocpc.baidu.com/ocpcapi/cb/actionCb?a_type=activate&a_value=0&s=123&ext_info={}
 */
@Service
public class BaiDuChannelReportService implements IChannelReportService {

    private static Logger log = LogFactory.getCommLog();

    // 信息流
    public static String REQUEST_URL = "http://ocpc.baidu.com/ocpcapi/cb/actionCb?a_type=activate&a_value=0&s=123&ext_info={}&join_type={}&bd_vid={}";

    // 大搜
    public static String REQUEST_URL_DASOU = "http://ocpc.baidu.com/ocpcapi/cb/actionCb?a_type=activate&a_value=0&ext_info={}&join_type={}&bd_vid={}";

//    public static List<String> DASOU_AKEY_LIST = new ArrayList<>();
//    static {
//        DASOU_AKEY_LIST.add("NTg0MjE5Mjc=");
//        DASOU_AKEY_LIST.add("NTg3Mzg1NDE=");
//        DASOU_AKEY_LIST.add("NTg3Mzg1NDA=");
//        DASOU_AKEY_LIST.add("NTg3Mzg1NDU=");
//
//        // 来钱呗
//        DASOU_AKEY_LIST.add("NjA0NTUyNDM=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDQ=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDU=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//
//        DASOU_AKEY_LIST.add("NjEwNzI1MDA=");
//        DASOU_AKEY_LIST.add("NjEwNzI1MDA==");
//
//        // 可借 大搜
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//        DASOU_AKEY_LIST.add("NjA0NTUyNDA=");
//
//    }

    @Resource
    ChannelActionMonitorRecordMapper channelActionMonitorRecordMapper;

    @Override
    public ReprotFlowResult registerActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        throw new RuntimeException("");
    }

    @Override
    public ReprotFlowResult sourceActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {

        ReprotFlowResult flowResult = new ReprotFlowResult();
        flowResult.setSuccess(false);

        JSONObject headObject = commonParam.getHeadObject();

        //oaid
//        String originparm1 = headObject.getString("originparm1");
        String originparm1 = headObject.getString("bdvid");

        // 返回失败的时候，把请求头信息存储下来
        flowResult.setParamInfo(JSON.toJSONString(headObject));
        if (StrUtil.isEmpty(originparm1)) {
            flowResult.setCode("-2");
            flowResult.setMessage("bdvid参数为空，不做处理");
            return flowResult;
        }

        ChannelActionMonitorRecord monitorRecord =
                channelActionMonitorRecordMapper.queryEntityByUnikeyAndActionType(originparm1, "CLICK", channelBaseInfo.getChannelCode());
        if (ObjectUtil.isEmpty(monitorRecord)) {
            flowResult.setCode("-3");
            flowResult.setMessage("可上报信息为空");
            return flowResult;
        }

        String akey = monitorRecord.getExtInfo();
        String userId = monitorRecord.getExtInfo1();

        boolean isDasou = BaiduAccountEnum.DASOU_USERID_LIST.contains(userId);
        String requestUrl = REQUEST_URL;
        if (isDasou){
            requestUrl = REQUEST_URL_DASOU;
        }

        String formatUrl = StrUtil.format(requestUrl, URLEncodeUtil.encode(monitorRecord.getCallbackInfo()), monitorRecord.getKeyType(), monitorRecord.getUniqueKey());
        String sign = SecureUtil.md5(formatUrl+akey);

        String reqUrl = formatUrl + "&sign=" + sign;

        log.info("【百度信息流上报】【注册】【开始请求】【reqestUrl】{}", reqUrl);
        String response = HttpUtil.createGet(reqUrl)
                .execute().body();
        log.info("【百度信息流上报】【注册】【开始结束】【result】{}", response);

        JSONObject resultObject = JSONObject.parseObject(response);
        Integer code = resultObject.getInteger("error_code");
        String message = resultObject.getString("error_msg");

        flowResult.setCode(String.valueOf(code));
        flowResult.setMessage(message);
        flowResult.setParamInfo(reqUrl);
        flowResult.setResultInfo(response);
        if (ObjectUtil.equals(code, Integer.valueOf("0"))){
            flowResult.setSuccess(true);
        }else{
            flowResult.setSuccess(false);
        }

        ChannelActionMonitorRecord updateEntity =new ChannelActionMonitorRecord();
        updateEntity.setId(monitorRecord.getId());
        updateEntity.setResultInfo(response);
        if (ObjectUtil.equals(code, Integer.valueOf(0))){
            updateEntity.setStatus("1");
        }else{
            updateEntity.setStatus(code+"");
        }
        int i = channelActionMonitorRecordMapper.updateById(updateEntity);

        return flowResult;
    }

    @Override
    public ReprotFlowResult downloadActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

    @Override
    public ReprotFlowResult payBuyActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

}
